﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


public partial class Change_Pasword2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!HttpContext.Current.Request.IsAuthenticated)
        {
            Response.Redirect("~/login.aspx");
        }
                      
    }
    
   
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        //Create SQL connection.
        string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;

        SqlConnection sqlConnection = new SqlConnection(strConnection);

        



        try
        {
            sqlConnection.Open();

            //Encrypt the current passwortextbox.
            String encrypttextboxpassword = SSTCryptographer.Encrypt(CurrentPassword.Text.Trim(), "SampleKey");
           
            String stringcmd1 = "SELECT UserName, Hash FROM [User] where UserName ='" + User.Identity.Name + "' and Hash='" + encrypttextboxpassword + "'";
            SqlCommand command = new SqlCommand(stringcmd1, sqlConnection);

            //Search current passwordtextbox is found in the database password.
            SqlDataReader dr;
            dr = command.ExecuteReader();

            if (dr.HasRows)
            {
                dr.Close();
                string finddatabasepwd = "SELECT hash FROM [User] where UserName ='" + User.Identity.Name + "'";

                SqlCommand command1 = new SqlCommand(finddatabasepwd, sqlConnection);

                //Check if the database password is the same as currentpassword textbox.
                String databasepwd = SSTCryptographer.Decrypt(command1.ExecuteScalar().ToString(), "SampleKey"); 


                if (databasepwd == CurrentPassword.Text)
                {

                    //Validate new password requirements with global settings
                    bool validpasswordlength = PasswordRequirement.validpasswordlength(NewPassword.Text);
                    int getpasswordlength = PasswordRequirement.getpasswordlength(NewPassword.Text);

                    if (validpasswordlength == false)
                    {
                        newpassworderror.Visible = true;
                        newpassworderror.Text = "Password length needs to be " + getpasswordlength + "";


                    }


                    else
                    {
                    bool validuppercase = PasswordRequirement.validuppercase(NewPassword.Text);
                    int getuppercase = PasswordRequirement.getupperchar(NewPassword.Text);

                    if (validuppercase == false)
                    {
                        newpassworderror.Visible = true;
                        newpassworderror.Text = "Password needs to contain " + getuppercase + " uppercase characters.";

                    }

                    else
                    {

                    bool validlowercase = PasswordRequirement.validlowercase(NewPassword.Text);
                    int getlowercase = PasswordRequirement.getlowerchar(NewPassword.Text);

                    if (validlowercase == false)
                    {
                        newpassworderror.Visible = true;
                        newpassworderror.Text = "Password needs to contain " + getlowercase + " lowercase characters.";

                    }
                    else
                    {
                        bool validspecialchar = PasswordRequirement.validspecialchar(NewPassword.Text);
                        int getspecialchar = PasswordRequirement.getspecialchar(NewPassword.Text);

                    if (validspecialchar == false)
                    {
                        newpassworderror.Visible = true;
                        newpassworderror.Text = "Password needs to contain " + getspecialchar + " special characters.";

                    }

                    else
                    {
                        dr.Close();

                        //Look if new password matches in password history database.
                        string databasepasspassword = "Select MinPastPassword from GlobalSetting";
                        SqlCommand cmddabasepasspassword = new SqlCommand(databasepasspassword, sqlConnection);
                        NewPassword.Text = SSTCryptographer.Encrypt(NewPassword.Text, "SampleKey");
                           
                        string gettopX = "SELECT  changeDate, userName, hash, hash2 FROM (SELECT TOP (" + cmddabasepasspassword.ExecuteScalar().ToString() + ") changeDate, userName, hash, hash2 FROM PasswordHistory WHERE userName ='" + User.Identity.Name + "' ORDER BY changeDate DESC) AS temp1 WHERE hash ='" + NewPassword.Text + "'";
                        SqlCommand GetPwdHistotryX = new SqlCommand(gettopX, sqlConnection);
                                    
                        dr = GetPwdHistotryX.ExecuteReader();
                                   
                        if (dr.HasRows)
                        {

                            dr.Close();
                            newpassworderror.Visible = true;
                            newpassworderror.Text = "Cannot use last " + cmddabasepasspassword.ExecuteScalar().ToString() + " passwords";

                        }


                    else
                    {


                        //Insert to database new password
                        dr.Close();

                        String stringcmd2 = "INSERT INTO [PasswordHistory] (userName,changeDate,hash,hash2) VALUES ('" + User.Identity.Name + "', @changedate, @hash,@hash2 )";
                        SqlCommand command2 = new SqlCommand(stringcmd2, sqlConnection);

                        SqlParameter changedate = new SqlParameter("@changedate", SqlDbType.DateTime);
                        changedate.Value = System.DateTime.Now;
                        command2.Parameters.Add(changedate);

                        // NewPassword.Text = SSTCryptographer.Encrypt(NewPassword.Text, "SampleKey");
                        SqlParameter hash = new SqlParameter("@hash", SqlDbType.VarChar);
                        hash.Value = NewPassword.Text.ToString();
                        command2.Parameters.Add(hash);

                        ConfirmPassword.Text = SSTCryptographer.Encrypt(ConfirmPassword.Text, "SampleKey");
                        SqlParameter hash2 = new SqlParameter("@hash2", SqlDbType.VarChar);
                        hash2.Value = ConfirmPassword.Text.ToString();
                        command2.Parameters.Add(hash2);

                        String stringcmd3 = "Update [User] set Hash='" + hash.Value.ToString() + "', Hash2 ='" + hash2.Value.ToString() + "' where UserName='" + User.Identity.Name + "'";
                        SqlCommand command3 = new SqlCommand(stringcmd3, sqlConnection);


                        //execute insert password to database and display sucess msg.
                        command2.ExecuteNonQuery();                              
                        command3.ExecuteNonQuery();
                                                                            
                        Response.Write("<script language='javascript'>alert('Password Successfully Change.');window.location.href='Default.aspx'</script>");             



                    }

                }

            }

        }
    }

  }
}

                    else
                    {
                        //Display wrong password
                        currentpassworderror.Visible = true;
                        currentpassworderror.ForeColor = System.Drawing.Color.Red;
                        currentpassworderror.Text = "Wrong password";
                    }
                
           
        }


        catch (Exception ex)
        {

            string errorMessage;
            errorMessage = ("The following error occured :rn" + ex.ToString());
            throw new Exception(errorMessage);
        }

        finally
        {
           
            sqlConnection.Close();

        }
       
    }

}